package com.vx.vxbug.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vx.vxbug.entities.User;

@Repository("userDao")
public class SqlUserDao implements IUserDao {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional(propagation = Propagation.REQUIRED)
	public void addUser(User b) {
		entityManager.persist(b);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public User getUserById(int id) {
		return entityManager.find(User.class, id);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public User getUserByLogin(String l) {
		return this.entityManager.createNamedQuery("User.getUserByLogin", User.class).setParameter("login", l).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public List<User> getAllUsers() {
		// List<User> result =
		// this.entityManager.createNamedQuery("User.getAllUsers",
		// User.class).getResultList();

		List<User> result = entityManager.createQuery("FROM User").getResultList();
		return result;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void updateUser(User b) {
		entityManager.refresh(b);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void deleteUser(User b) {
		entityManager.remove(b);
	}

}
